Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Array and Objects

Array of Objects

In Java, an array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. An array of objects, also known as an object array in Java, is an array that can hold objects of any type or class. Specifically, it can hold any type of data such as integers, strings, doubles, or any other Java objects. Here's a simple example of how to declare and initialize an array of objects in Java:
Array of objects example in java public class Main { public static void main(String[] args) { // Declare and initialize an array of Student objects Student[] students = new Student[3]; students[0] = new Student("John", 20); students[1] = new Student("Jane", 21); students[2] = new Student("Doe", 22); // Access elements in the array for (Student student : students) { System.out.println("Name: " + student.name + ", Age: " + student.age); } } } public class Student { String name; int age; // Constructor public Student(String name, int age) { this.name = name; this.age = age; } }

Output

Name: John, Age: 20 Name: Jane, Age: 21 Name: Doe, Age: 22
In this example, we have a `Student` class with two properties: `name` and `age`. We then create an array of `Student` objects and initialize it with three `Student` instances. We can access the properties of each `Student` object in the array using a for-each loop. Remember, since arrays are objects in Java, you can have arrays of any type of object you want. This includes primitives like `int`, `float`, `boolean`, etc., as well as non-primitive objects like `String`, `Date`, `ArrayList`, or any user-defined objects. This makes arrays a very powerful and flexible tool in Java programming.

  📌TAGS

★array ★ java ★method ★object ★ example

Tutorials